#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/7/2 14:42
# @Author : wn 
# @File: hisQuery.py
# @SoftWare: PyCharm
# @Site:
# @Table:
# ｡◕‿◕｡｡◕‿◕｡｡◕‿◕｡
import datetime
import json

from django.db.models import Max
from django.shortcuts import render
from django.views import View

from trade.search_page import *
from utils.service import my_page


# 默认每页20 条
# 默认显示一周的持仓
# 可查询最多一年内的持仓

class HisQuery(View):
    def get(self, request):
        # 当前在第几页
        off = request.GET.get('offset', None)
        # 一页几条
        lim = request.GET.get('limit', None)
        if lim is None:
            return render(request, 'hisQuery.html', {'url': '/trade/his_query'})
        else:
            # t_ruleposition 持仓
            rp_list = []
            rp_qs = Ruleposition.objects.using('quantPaperDB').all().order_by("ruleid")
            # tm_dict = rp_qs.aggregate(Max("tradingday"))
            # timeMax_str = tm_dict['tradingday__max']  # str
            # if timeMax_str == None:
            timeMax_str = datetime.datetime.now().strftime("%Y%m%d")
            # 字符串转时间元组
            datetime_7 = datetime.datetime.strptime(timeMax_str, "%Y%m%d") - datetime.timedelta(days=7)
            str_7 = datetime.datetime.strftime(datetime_7, "%Y%m%d")
            rpFilter_qs = Ruleposition.objects.using('quantPaperDB').filter(tradingday__gte=str_7,
                                                                            tradingday__lt=timeMax_str).order_by(
                "ruleid",
                "instrumentid")

            for item in rpFilter_qs:
                rp_dict = {}
                rp_dict['tradingday'] = item.tradingday
                rp_dict['ruleid'] = item.ruleid
                rp_dict['position'] = item.position
                rp_dict['instrumentid'] = item.instrumentid
                stgname = ''
                stg = Strategy.objects.using('quantWebDB').filter(stgid=item.ruleid)
                if len(stg) != 0:
                    stgname = stg[0].stgname
                rp_dict['rulename'] = stgname
                rp_list.append(rp_dict)

            # 排序 Ruleposition
            for item in rp_list:
                if (item.get('tradingday') is None):
                    item['tradingday'] = '-1'
            result_list_sorted = sorted(rp_list, key=itemgetter('tradingday'), reverse=True)
            result = my_page(result_list_sorted, lim, off)
            return JsonResponse(result)

    def post(self, request):
        if request.POST.get('hisSearchPosition_search', None):
            # 前端查询条件
            data = json.loads(request.POST.get("data"))
            instrumentid = data.get("instrumentid", None)  # if no condition value is str ''
            ruleid = data.get("ruleid", None)
            stgname = data.get("stgname", None)
            pl_envid = data.get("pl_envid", None)
            hisStartTime = data.get("starttime", None)
            hisEndTime = data.get("endtime", None)
            # 2020-07-01 2020-07-09 <class 'str'> <class 'str'>
            if pl_envid == "1":  # 仿真环境
                jsonRes = search_daySearch(instrumentid=instrumentid, stgname=stgname, ruleid=ruleid, type='2',
                                           pflag="2", hisStartTime=hisStartTime, hisEndTime=hisEndTime)
            elif pl_envid == "2":
                jsonRes = search_liveSearch(instrumentid=instrumentid, stgname=stgname, ruleid=ruleid, type='2',
                                            pflag="2", hisStartTime=hisStartTime, hisEndTime=hisEndTime)
            return jsonRes
